package org.setamv.springcloud.hystrix.raw.command.circuitbreaker;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * 测试断路器强制打开时执行命令的效果，其结果是总是执行回退逻辑
 */
public class ForceOpenCommand extends HystrixCommand<String> {

    /**
     *
     * @param forceOpen true-强制打开命令的断路器；false-不打开断路器
     */
    public ForceOpenCommand(boolean forceOpen) {
        super(Setter
                .withGroupKey(HystrixCommandGroupKey.Factory.asKey("testGroup"))
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withCircuitBreakerForceOpen(forceOpen)));
    }

    @Override
    protected String run() throws Exception {
        // 使用HttpClient访问url
        String url = "http://setamv.tech:9091/greetings/from/setamv";
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpResponse response = httpClient.execute(httpGet);
        String greetings = EntityUtils.toString(response.getEntity());
        return greetings;
    }

    @Override
    protected String getFallback() {
        return "circuit breaker force opened, fall back.";
    }
}
